package com.itcs.app.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.itcs.app.properties.BsConfig;
import com.itcs.app.properties.IXzzfConfig;
import com.itcs.app.properties.PropertiesService;
import com.itcs.app.properties.ZsConfig;
import com.itcs.box.util.LogUtils;

/**
 * 现在支付
 * @author Administrator
 *
 */
public class XzzfPay {
	private static Log logger = LogFactory.getLog(XzzfPay.class);

	/**
	 * 被扫
	 * @param payChannelType  支付渠道 12 支付宝  13 微信
	 * @param mhtOrderName  订单名称
	 * @param mhtOrderDetail  订单详情
	 * @param mhtOrderAmt  订单金额
	 * @param mhtReserved 商户保留域
	 * @param mhtOrderNo  订单号
	 * @param channelAuthCode  支付授权码
	 * @return
	 */
	public static Map<String, String> bs(String mhtOrderName,String mhtOrderDetail,String mhtOrderAmt,String mhtReserved,String mhtOrderNo,String channelAuthCode) {
		Map<String, String> map =new  HashMap<String, String>();
		  //拿到配置信息
//        InputStream propertiesInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("bsconfig.properties");
//        Properties properties = new Properties();
//        try {
//			properties.load(propertiesInput);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
        String caStr = channelAuthCode.substring(0, 2);
        
        String payChannelType = null;
        if(caStr.equals("25") || caStr.equals("26") || caStr.equals("27") || caStr.equals("28") || caStr.equals("29") || caStr.equals("30")){
        	payChannelType="12";
        }else{
        	payChannelType="13";
        }
        
        
    	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");	
		
    	 BsConfig bsConfig = PropertiesService.getBsConfig();
    	
		//商户自己的订单数据
		String funcode = IXzzfConfig.FUNCODE_WP001;
		String deviceType = bsConfig.getDeviceType();
		String version = bsConfig.getVersion();
		String mhtOrderType = bsConfig.getMhtOrderType();
		String mhtOrderStartTime = dateFormat.format(new Date());
		String notifyUrl = bsConfig.getNotifyUrl();
		String mhtCharset = bsConfig.getMhtCharset();
		String mhtOrderTimeOut = bsConfig.getMhtOrderTimeOut();
		String mhtSignType =  bsConfig.getMhtSignType();
		String mhtCurrencyType = bsConfig.getMhtCurrencyType();
		
		String appId = bsConfig.getAppId();
		String appKey = bsConfig.getAppKey();
//		String subappid = null;
//		if("12".equals(payChannelType)){//支付宝
//			appId =  (String) properties.get("appIdzfb");
//			appKey =(String) properties.get("appKeyzfb");
//		}else if("13".equals(payChannelType)){//微信
//			appId =  (String) properties.get("appIdwx");
//			appKey =(String) properties.get("appKeywx");
////			subappid =(String) properties.get("subappid");
//		}else{
////			目前不支付其它类型
//		}
		
	
		//做MD5签名
		Map<String, String> dataMap = new HashMap<String, String>();
		dataMap.put("appId", appId);
		dataMap.put("channelAuthCode", channelAuthCode);
		dataMap.put("deviceType", deviceType);
		dataMap.put("funcode",funcode);
		dataMap.put("mhtOrderNo", mhtOrderNo);
		dataMap.put("mhtOrderName", mhtOrderName);
		dataMap.put("version", version);
		dataMap.put("mhtCurrencyType", mhtCurrencyType);
		dataMap.put("mhtOrderAmt", mhtOrderAmt);
		dataMap.put("mhtOrderDetail", mhtOrderDetail);
		dataMap.put("mhtOrderType", mhtOrderType);
		dataMap.put("mhtOrderStartTime", mhtOrderStartTime);
		dataMap.put("mhtOrderTimeOut", mhtOrderTimeOut);
		dataMap.put("notifyUrl", notifyUrl);
		dataMap.put("mhtCharset", mhtCharset);
		dataMap.put("payChannelType", payChannelType);
		dataMap.put("mhtSignType", mhtSignType);
//		if("13".equals(payChannelType)){
//			dataMap.put("subappid", subappid);
//		}
		
		//商户保留域， 可以不用填。 如果商户有需要对每笔交易记录一些自己的东西，可以放在这个里面
		dataMap.put("mhtReserved", mhtReserved);
		
		String mhtSignature = MD5Facade.getFormDataParamMD5(dataMap, appKey, "UTF-8","2");
		logger.info(LogUtils.build("xzzfbs", "现在支付被扫", "参数构建完成",JSON.toJSONString(dataMap)));
		long startTime = System.currentTimeMillis();
		String jxjgBak=HttpUtil.httpRequest(IXzzfConfig.REQUEST_URL, IXzzfConfig.REQUEST_METHOD, mhtSignature);
		logger.info(LogUtils.build("xzzfbs", "现在支付被扫", "接口调用完成,耗时:"+(System.currentTimeMillis()-startTime),jxjgBak));
		map = (Map<String, String>) JSON.parse(loadJson(jxjgBak));
		
		return map;		
	}
	
	/**
	 *  公众号
	 *  SpayChannelType//支付渠道
	 *	mhtOrderName//订单名称
	 *	mhtOrderDetail//订单详情
	 *	mhtOrderAmt//订单金额
	 *	mhtReserved//mhtReserved
	 * */
	@SuppressWarnings("static-access")
	public static Map<String, String> gzh(String payChannelType,String mhtOrderName,String mhtOrderDetail,String mhtOrderAmt,String mhtReserved,String mhtOrderNo) {
    	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		
    	ZsConfig zsConfig = PropertiesService.getZsConfig();
    	
		String appId =  zsConfig.getAppId();
		String appKey = zsConfig.getAppKey();
		
		//商户自己的订单数据
		String funcode =  IXzzfConfig.FUNCODE_WP001;
		String deviceType =  zsConfig.getDeviceType();
		String version =  zsConfig.getVersion();
		String mhtCurrencyType = zsConfig.getMhtCurrencyType();
		String outputType = zsConfig.getOutputType();
		String mhtSignType = zsConfig.getMhtSignType();
		String notifyUrl = zsConfig.getNotifyUrl();
		String frontNotifyUrl = zsConfig.getFrontNotifyUrl();
		String mhtCharset = zsConfig.getMhtCharset();
		String mhtOrderType = zsConfig.getMhtOrderType();
		String mhtOrderStartTime = dateFormat.format(new Date());
		
		//做MD5签名
		Map<String, String> dataMap = new HashMap<String, String>();
		dataMap.put("appId", appId);
		dataMap.put("deviceType", deviceType);
		dataMap.put("funcode",funcode);
		dataMap.put("mhtOrderNo", mhtOrderNo);
		dataMap.put("mhtOrderName", mhtOrderName);
		dataMap.put("version", version);
		dataMap.put("mhtCurrencyType", mhtCurrencyType);
		dataMap.put("mhtOrderAmt", mhtOrderAmt);//String.valueOf((Double.valueOf(mhtOrderAmt).intValue()))
		dataMap.put("mhtOrderDetail", mhtOrderDetail);
		dataMap.put("mhtOrderType", mhtOrderType);
		dataMap.put("mhtOrderStartTime", mhtOrderStartTime);
		dataMap.put("notifyUrl", notifyUrl);
		dataMap.put("frontNotifyUrl", frontNotifyUrl);
		dataMap.put("mhtCharset", mhtCharset);
		dataMap.put("outputType", outputType);
		dataMap.put("payChannelType", payChannelType);
		dataMap.put("mhtSignType", mhtSignType);
		
		//商户保留域， 可以不用填。 如果商户有需要对每笔交易记录一些自己的东西，可以放在这个里面
		dataMap.put("mhtReserved", mhtReserved);
		
		String mhtSignature = MD5Facade.getFormDataParamMD5(dataMap, appKey, "UTF-8","1");
		
		dataMap.put("mhtSignature", mhtSignature);
		
        String tollFareYStr = new BigDecimal(mhtOrderAmt).divide(new BigDecimal(100),2, RoundingMode.HALF_UP).toString();
		dataMap.put("mhtOrderAmtStr", tollFareYStr);
		
		logger.info(LogUtils.build("xzzfgzh", "现在支付公众号主扫", "参数构建完成",JSON.toJSONString(dataMap)));
		return dataMap;
	}
	
	/**
	 *  公众号-查询
	 *  SpayChannelType//支付渠道
	 *	mhtOrderName//订单名称
	 *	mhtOrderDetail//订单详情
	 *	mhtOrderAmt//订单金额
	 *	mhtReserved//mhtReserved
	 * */
	public static Map<String, String> gzhcx(String mhtOrderNo,String payChannelType) {
		return caxun(mhtOrderNo,payChannelType,PropertiesService.getZsConfig());
	}
	/**
	 *  被扫-查询
	 *  SpayChannelType//支付渠道
	 *	mhtOrderName//订单名称
	 *	mhtOrderDetail//订单详情
	 *	mhtOrderAmt//订单金额
	 *	mhtReserved//mhtReserved
	 * */
	public static Map<String, String> bscx(String mhtOrderNo,String payChannelType) {
		return caxun(mhtOrderNo,payChannelType,PropertiesService.getBsConfig());
	}
	/**
	 *  公众号-查询
	 *  SpayChannelType//支付渠道
	 *	mhtOrderName//订单名称
	 *	mhtOrderDetail//订单详情
	 *	mhtOrderAmt//订单金额
	 *	mhtReserved//mhtReserved
	 * */
	@SuppressWarnings("static-access")
	public static Map<String, String> caxun(String mhtOrderNo,String payChannelType,IXzzfConfig xcconfig) {

		//商户自己的订单数据
		String funcode =  IXzzfConfig.FUNCODE_MQ002;
		String version =  xcconfig.getVersion();
		String deviceType =  xcconfig.getDeviceType();
		String mhtCharset = xcconfig.getMhtCharset();
		String mhtSignType = xcconfig.getMhtSignType();
		
		String appId = xcconfig.getAppId();
		String appKey = xcconfig.getAppKey();
		
		//做MD5签名
		Map<String, String> dataMap = new HashMap<String, String>();
		dataMap.put("funcode",funcode);
		dataMap.put("version", version);
		dataMap.put("deviceType", deviceType);
		dataMap.put("appId", appId);
		//mhtOrderNo
		dataMap.put("mhtCharset", mhtCharset);
		dataMap.put("mhtSignType", mhtSignType);
		
		//商户保留域， 可以不用填。 如果商户有需要对每笔交易记录一些自己的东西，可以放在这个里面
		dataMap.put("mhtOrderNo", mhtOrderNo);
		
		
		String mhtSignature = MD5Facade.getFormDataParamMD5(dataMap, appKey, "UTF-8","2");
		
		dataMap.put("mhtSignature", mhtSignature);
		
		logger.info(LogUtils.build("xzzfcx", "现在支付查询", "参数构建完成",JSON.toJSONString(dataMap)));
		
		long startTime = System.currentTimeMillis();
		
		String httpResult=HttpUtil.httpRequest(IXzzfConfig.REQUEST_URL, IXzzfConfig.REQUEST_METHOD, mhtSignature);
		
		logger.info(LogUtils.build("xzzfbs", "现在支付查询", "接口调用完成,耗时:"+(System.currentTimeMillis()-startTime),httpResult));
		
		Map<String, String> map = (Map<String, String>) JSON.parse(loadJson(httpResult));
		return map;
	}
	/**
	 * 通过订单号查看订单是否成功
	 * @param mhtOrderNo
	 * @return
	 */
	public static Boolean gzhcxIs(String mhtOrderNo,String payChannelType) {
		if(mhtOrderNo==null){
			return false;
		}
		Map<String, String> map = gzhcx(mhtOrderNo,payChannelType);
		String transStatus = map.get("transStatus");
		if("A001".equals(transStatus)){
			return true;
		}else{
			return false;
		}
	}
	
	public static String loadJson (String url) {  
		url=url.replace("[", "-");
		url=url.replace("]", "-");
		url=url.replace("#", "-");
		int sun = 0;
		  int count = 0;
		  String json = "{";
		  String data = "";
		
		  StringBuffer sb = new StringBuffer();
		  StringBuffer sb2 = new StringBuffer();
		  String arry = url;
		  // 计算出字符串里有多少个&符号
		  for (int i = 0; i < arry.length(); i++) {
		   if ("&".equals(arry.substring(i, i + 1))) {
		    sun++;
		   }
		  }
		  String a[] = arry.split("[&]");//以&符号分隔
		  String test[]=null;
		  //将分隔出来的字符串加上，
		  for (int i = 0; i < sun + 1; i++) {
			
			  
			  String[]  strs= a[i].toString().split("[=]");
			  if(strs.length>2){
				  String ss ="";
				 for (int j=0 ;j<strs.length ;j++){//有时返回多个=号
					 if(j==0){
						 ss=ss+strs[j]+"="+strs[j+1];
					 }else{
						 if(j==strs.length-1){
						 }else{
							 ss=ss+"|"+strs[j+1];
						 }
						
						 
					 }
				 }
				  
				  sb.append(ss + ",");
			  }else{
				  sb.append(a[i] + ",");
			  }
			  
			
		  }
		  
		  
		  
		  //以=分隔
		  String[] c = sb.toString().split("[=]");
		  //将分隔出来的字符串加上，
		  for (int j = 0; j < c.length; j++) {
		   sb2.append(c[j] + ",");
		  }
		  //去掉最后面两个,
		  String result = sb2.toString().substring(0, sb2.length() - 2);
		  // 计算出字符串里有多少个,符号
		  for (int i = 0; i < result.length(); i++) {
		   if (",".equals(result.substring(i, i + 1))) {
		    count++;
		   }
		  }
		  //以，分隔
		  String[] d = result.toString().split("[,]");
		  for (int i = 0; i < count + 1; i++) {
		   if (i % 2 != 0) {//字符下标为奇数时加上，
		    data += "\"" + d[i] + "\",";
		   } else {
		    data += "\"" + d[i] + "\":";
		   }
		  }
		  //拼接json格式
		  String jsonArray = (json + data).substring(0,
		    (json + data).length() - 1)
		    + "}";
		  System.out.println(jsonArray.replace("|", "="));
		  return jsonArray.replace("|", "=");
    }  
	
	

}
